<template>
  <div class="compact-container">
    <!-- 条件查询行，新增按钮在最右边 -->
    <div class="search-row">
      <span class="search-label">供应商名称：</span>
      <el-input v-model="vendor_name" size="small" class="search-input" />
      <span class="search-label">供应商编码：</span>
      <el-input v-model="vendor_code" size="small" class="search-input" />
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">新增</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table :data="tableData" stripe border 
                style="width: 100%"
                :cell-style="{ textAlign: 'center', padding: '4px 0' }"
                :header-cell-style="{
                  textAlign: 'center',
                  background: '#f5f7fa',
                  fontWeight: 'bold',
                  position: 'sticky',
                  top: 0,
                  padding: '4px 0',
                  height: '36px'
                }"
                :row-style="{ height: '36px' }">
        <!-- 表格列定义保持不变 -->
        <el-table-column fixed width="180" prop="vendor_code" label="供应商编码">
          <template #default="scope">
            <el-link type="primary" @click="infoPage(scope.row)">{{ scope.row.vendor_code }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="vendor_name" label="供应商昵称" width="130" />
        <el-table-column prop="vendor_classify" label="供应商分类" width="150">
          <template #default="scope">{{ statusValue(scope.row.vendor_classify) }}</template>
        </el-table-column>
        <el-table-column prop="vendor_grade" label="供应商等级" width="180">
          <template #default="scope">
            <el-rate :model-value="scope.row.vendor_grade" :colors="colors" disabled size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="vendor_starttime" label="签约开始时间" width="200" />
        <el-table-column prop="vendor_endtime" label="签约结束时间" width="200" />
        <el-table-column prop="vendor_term" label="结算期限" width="150">
          <template #default="scope">{{ statusValue1(scope.row.vendor_term) }}</template>
        </el-table-column>
        <el-table-column prop="vendor_address" label="供应商地址" width="200" />
        <el-table-column prop="vendor_rep_id" label="负责人" width="150">
          <template #default="scope">{{ userValue(scope.row.vendor_rep_id) }}</template>
        </el-table-column>
        <el-table-column prop="vendor_phone" label="联系电话" width="150" />
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.vendor_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 保持居中的分页组件 -->
      <div class="pagination-center">
        <el-pagination
          small
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, markRaw } from 'vue'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import { useStore } from 'vuex'

export default {
  setup() {
    const store = useStore()

    const router = useRouter();
    const vendor_code = ref("");
    const vendor_name = ref("");
    const tableData = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const pageCount = ref(0);
    const statusOptios = ref([]);
    const settlement = ref([]);
    const userOptions = ref([]);
    const deptOptions = ref([]);

    onMounted(() => {
      getClassify();
      getClassify1();
      getDept();
      getUser();
      fill();
      count();
    });

    async function fill() {
      try {
        const result = await axios.get("http://localhost:5181/api/Values/Pinv_VendorFYWhere", {
          params: { Vendor_name: vendor_name.value, Vendor_code: vendor_code.value, currentPage: currentPage.value, pageSize: pageSize.value },
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        tableData.value = result.data.map(item => ({
          ...item,
          vendor_starttime: formatDate(item.vendor_starttime),
          vendor_endtime: formatDate(item.vendor_endtime)
        }));
      } catch (err) {
        console.error(err);
      }
    }

    async function count() {
      try {
        const result = await axios.get("http://localhost:5181/api/Values/Pinv_VendorCount", {
          params: { Vendor_name: vendor_name.value, Vendor_code: vendor_code.value },
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        pageCount.value = result.data;
      } catch (err) {
        console.error(err);
      }
    }

    async function getClassify() {
      try {
        const result = await axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
          params: { dict_type: "Customer_classify" },
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        statusOptios.value = result.data;
      } catch (err) {
        console.error(err);
      }
    }

    function statusValue(row) {
      if (!row) return "无";
      const parentDept = statusOptios.value.find((classify) => classify.dict_value == row);
      return parentDept ? parentDept.dict_label : "无";
    }

    async function getClassify1() {
      try {
        const result = await axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
          params: { dict_type: "settlement_period" },
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        settlement.value = result.data;
      } catch (err) {
        console.error(err);
      }
    }

    function statusValue1(row) {
      if (!row) return "无";
      const parentDept = settlement.value.find((classify) => classify.dict_value == row);
      return parentDept ? parentDept.dict_label : "无";
    }

    async function getUser() {
      try {
        const result = await axios.get("http://localhost:5181/api/User/GetUsers", {
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        userOptions.value = result.data;
      } catch (err) {
        console.error(err);
      }
    }

    async function getDept() {
      try {
        const result = await axios.get("http://localhost:5181/api/Dept/DeptOpt", {
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        deptOptions.value = result.data;
      } catch (err) {
        console.error(err);
      }
    }

    function userValue(row) {
      if (!row) return "无";
      const parentUser = userOptions.value.find((user) => user.user_id == row);
      return parentUser ? parentUser.user_name : "无";
    }

    function formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    }

    function infoPage(row) {
      store.commit('PO_UpdeteArray', row)
      router.push({
        path: '/main/Pinv/vendorinfo',
        // query: { rowData: JSON.stringify(row) }
      });
    }

    function query() {
      fill();
      count();
    }

    function reset() {
      vendor_code.value = "";
      vendor_name.value = "";
      fill();
      count();
    }

    function handleSizeChange(val) {
      pageSize.value = val;
      fill();
    }

    function handleCurrentChange(val) {
      currentPage.value = val;
      fill();
    }

    function addEdit() {
      router.push({ path: '/main/Pinv/vendorAdd' });
    }

    function handleEdit(row) {
      store.commit('PO_UpdeteArray', row)
      router.push({
        path: '/main/Pinv/vendorUpdate',
        // query: { rowData: JSON.stringify(row) }
      });
    }

    function handleDelete(row) {
      ElMessageBox.confirm(
        '此操作将删除该产品信息，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(Delete),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
      .then(async() => {
        const rowData = { Vendor_id: row, Del_flag: "1" };
        await axios.put('http://localhost:5181/api/Values/Pinv_VendorDelete', rowData, {
          headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        ElMessage.success("删除成功");
        fill();
        count();
      })
      .catch((error) => {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          ElMessage.error("删除失败");
        }
      });
    }

    return { 
      vendor_code, vendor_name, tableData, settlement, currentPage, 
      deptOptions, userOptions, statusValue, handleEdit, statusValue1, 
      infoPage, pageSize, pageCount, userValue, handleDelete, 
      handleCurrentChange, handleSizeChange, reset, query, addEdit 
    };
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
}

/* 更紧凑的搜索行，新增按钮在最右边 */
.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -50px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

/* 表格区域 */
.table-wrapper {
  margin-top: 6px;
}

/* 表格紧凑样式 */
:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}

:deep(.el-link) {
  font-size: 13px;
}

/* 分页居中 */
.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}
</style>